package com.rzico.sbl.ui.mine

import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityShopDeviceBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.QRType
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.viewmodel.ShopViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.showHintDialog

class ShopDeviceActivity : BaseActivity(R.layout.activity_shop_device) {

    private val mBinding by lazy { ActivityShopDeviceBinding.bind(getRootView()) }

    override fun getViewModel() = get<ShopViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        mBinding.deviceCode.text = "设备号：${intent.getExtra("account")}"
        mBinding.devicePwd.text = "设备密钥：${intent.getExtra("pwd")}"
    }

    override fun initListener() {
        mBinding.apply {
            btBind.oneClick {
                startActivityEx<ScanActivity>(
                    "mode" to QRType.PRINT,
                    "from" to "shop",
                    "shopId" to intent.getExtra("shopId")
                )
            }

            btUnbind.oneClick {
                showHintDialog(
                    title = "解除绑定",
                    hint = "确定要解除绑定该设备吗？",
                    onSure = {
                        getViewModel()
                            .request(
                                requestUrl = BaseUrl.shopPntDel,
                                params = arrayOf(
                                    "shopId" to intent.getExtra("shopId")
                                ),
                                onSuccess = {
                                    showToast("解绑成功！")

                                    // 刷新店铺列表
                                    LiveEventBus
                                        .get("shopList")
                                        .post("refresh")

                                    finishView()
                                }
                            )
                    }
                )
            }
        }

        observe<String>("shopList") {
            if ("," in it) {
                val items = it.split(",")
                mBinding.deviceCode.text = "设备号：${items[0]}"
                mBinding.devicePwd.text = "设备密钥：${items[1]}"
            }
        }
    }

}